package com.haojiang.mh.ui.activity

import android.app.Dialog
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.haojiang.mh.R
import com.haojiang.mh.cache.Const
import com.haojiang.mh.service.ble.BleHandle
import com.haojiang.mh.service.event.OneEvent
import com.haojiang.mh.ui.adapter.BtDeviceListAdapter
import com.haojiang.mh.ui.adapter.ItemSpaceDecoration
import com.haojiang.mh.ui.adapter.OnItemChildClickListener
import com.haojiang.mh.ui.base.BaseActivity
import com.haojiang.mh.utils.KLog
import com.haojiang.mh.utils.MUtil
import kotlinx.android.synthetic.main.activity_common_title.*
import kotlinx.android.synthetic.main.activity_device_list.*
import kotlinx.coroutines.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 设备列表
 *
 * Created by ZapFive on 2019-05-26.
 *
 * wuzhuang@mirahome.me
 */
class DeviceListActivity : BaseActivity() {

    private val deviceList = ArrayList<BleDevice>()
    private lateinit var deviceListAdapter: BtDeviceListAdapter
    private var delayScanJob: Job? = null
    private var connectJob: Job? = null
    private var isManualCancelScan = false
    var retryTimes = 0

    //region 生命周期
    override fun getLayoutId() = R.layout.activity_device_list

    override fun getTitleName() = ""

    override fun initActivity() {
    }

    override fun initView() {
        tv_activity_right.setText(R.string.tv_refresh)
        tv_activity_right.visibility = View.VISIBLE
        tv_activity_right.setOnClickListener {
            delayHandleReScan()
        }
        rv_device_list.layoutManager = LinearLayoutManager(context)
        deviceListAdapter = BtDeviceListAdapter(context, deviceList)
        deviceListAdapter.setItemClickListener(itemClickListener)
        rv_device_list.adapter = deviceListAdapter
        rv_device_list.addItemDecoration(ItemSpaceDecoration(context, 15, 7, 8, 10))

        if (isSupportBle) {
            if (BleHandle.instance.isBleEnable()) {
                BleHandle.instance.scanDevice(bleScanCallback)
            } else {
                redirectWithExtraAndFinish(1, SearchDeviceFailActivity::class.java)
            }
        } else {
            context.finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (connectJob != null) {
            MUtil.cancelJob(connectJob)
        }
    }

    override fun onPause() {
        isManualCancelScan = true
        BleHandle.instance.cancelScan()
        super.onPause()
    }

    override fun onBackClick() {
        if (BleHandle.instance.isConnected()) {
            KLog.d("------onBackClick")
            BleHandle.instance.disConnectDevice()
            BleHandle.instance.onDeviceDisconnect(true)
        } else {
            KLog.d("---------onback")
            super.onBackClick()
        }
    }

    //endregion

    //region 重新扫描最少间隔4秒执行一次

    private fun delayHandleReScan() {
        MUtil.cancelJob(delayScanJob)
        delayScanJob = GlobalScope.launch {
            withContext(Dispatchers.Main) {
                showLoadingDialog()
                isManualCancelScan = true
                BleHandle.instance.cancelScan()
                deviceList.clear()
                deviceListAdapter.notifyDataSetChanged()
            }
            delay(4_000L)
            isManualCancelScan = false
            BleHandle.instance.scanDevice(bleScanCallback)
        }
    }


    //endregion

    //region Listener

    private val itemClickListener = OnItemChildClickListener { _, any, _ ->
        val device = any as BleDevice
        BleHandle.instance.currDevice = device
        retryTimes = 0;
        //如果当前已连接，则直接跳转成功
        if (BleHandle.instance.isConnected()) {
            redirectWithExtra(Const.CONNECT_DEVICE_SUCCESS, CommonSuccessActivity::class.java)
        } else {
            showConnectDialog()
            connectJob = GlobalScope.launch {
                repeat(5) { i ->
                    retryTimes = i
                    KLog.d("i==" + i + "---" + BleHandle.instance.isConnected())
                    if (!BleHandle.instance.isConnected()) {
                        BleHandle.instance.connectDevice()
                        delay(3_000L)
                        if (!BleHandle.instance.isConnected()) {
                            BleHandle.instance.disConnectDevice()
                            BleHandle.instance.onDeviceDisconnect(true)

                        }
                    }
                }
            }
        }
    }

    /**
     * 蓝牙扫描结果回调
     */
    private val bleScanCallback = object : BleScanCallback() {
        override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
            if (isManualCancelScan) return
            hideLoadingDialog()
            if (scanResultList.isNullOrEmpty()) {
                redirectWithExtraAndFinish(2, SearchDeviceFailActivity::class.java)
            } else {
                if (deviceList.size != scanResultList.size) {
                    deviceList.clear()
                    deviceList.addAll(scanResultList)
                    deviceListAdapter.notifyDataSetChanged()
                }
            }
        }

        override fun onScanStarted(success: Boolean) {
            showLoadingDialog()
            KLog.d("onScanStarted  :$success")
        }

        override fun onScanning(bleDevice: BleDevice?) {
            hideLoadingDialog()
            KLog.d("onScanning  :${bleDevice?.mac}")
            if (bleDevice == null) return
            deviceList.add(bleDevice)//扫描结果立刻添加到列表中
            deviceListAdapter.notifyItemInserted(deviceList.size - 1)
        }
    }
    //endregion

    //region Loading Dialog
    private var connectDialog: Dialog? = null

    private fun showConnectDialog() {
        if (connectDialog == null) {
            connectDialog = Dialog(context, R.style.CommonDialogStyle)
            val view = LayoutInflater.from(context).inflate(R.layout.layout_connect_device_dialog, null, false)
            connectDialog!!.setContentView(view)
            connectDialog!!.setCancelable(true)
            connectDialog!!.setCanceledOnTouchOutside(false)
        }
        if (!context.isFinishing && !connectDialog!!.isShowing) {
            connectDialog!!.show()
        }
    }

    private fun hideConnectDialog() {
        if (connectDialog != null && connectDialog!!.isShowing) {
            connectDialog!!.dismiss()
        }
    }
    //endregion

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveEvent(event: OneEvent) {
        when (event.type) {
            Const.CONNECT_DEVICE -> {
                if (event.getIntValue() == Const.OK_RESULT) {
                    hideConnectDialog()
                    redirectWithExtra(Const.CONNECT_DEVICE_SUCCESS, CommonSuccessActivity::class.java)
                } else {
                    if(retryTimes == 4){
                        hideConnectDialog()
                        showLongToast(getString(R.string.tip_connect_device_fail))
                    }
                }
            }
            Const.DISCONNECT_DEVICE -> context.finish()
        }
    }
}